package com.egene.tw.fcm;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.egene.tw.R;
import com.egene.tw.activity.StartActivity_;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import java.util.Map;

/**
 * Created by albert on 2017/11/4.
 */

public class AppFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "AppFirebaseMessagingService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d(TAG, "onMessageReceived: ");

        Map<String, String> data = remoteMessage.getData();
        String title = "";
        String body = "";
        if(data != null){
            title = data.get("title");
            body = data.get("body");
            sendNotification(title, body);
        }else {
            RemoteMessage.Notification notification = remoteMessage.getNotification();
            if(notification != null){
                title = notification.getTitle();
                body = notification.getBody();
                sendNotification(title, body);
            }
        }
        Log.d(TAG, "onMessageReceived: title - " + title);
        Log.d(TAG, "onMessageReceived: body - " + body);
    }

    private void sendNotification(String title, String messageBody) {
        Context context = getApplicationContext();
        Intent intent = new Intent(getApplicationContext(), StartActivity_.class);
        PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(),
                (int) System.currentTimeMillis(), intent, 0);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
                .setContentTitle(title)
                .setContentText(messageBody)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentIntent(pIntent)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification =  notificationBuilder.build();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(1, notification);
    }
}
